package serv;

import java.io.IOException;
import java.net.*;

import engine.*;

public class Server extends Thread {

	protected static final int PORT = 49500; 
	protected ServerSocket listen;
	
	int nb_thread;
	int nb_players;
	int nb_fanions;
	
	//World contains all the players, flags, ... 
	protected World w;
	
	public Server () { 

		try { 
			listen = new ServerSocket(PORT);
		} 
		catch (IOException e) { 
			System.err.println(e.getMessage()); 
			System.exit(1); 
		} 
		System.out.println("Server listening on port : "+PORT);
		
		this.nb_thread = 0;
		this.nb_players = 10;
		this.nb_fanions = 1;
		
		w = new World(nb_players, nb_fanions, 480, 272);
		
		for (int i=0; i<nb_fanions; i++){
			w.getFanion()[i] = new Fanion(i, i);
		}
		
		this.start(); 
	}
	
	public void run () { 
		
		try {
			
			//Threads that control all the clients
			ThreadManager tm = new ThreadManager(nb_players);

			// Whenever a client is connected
			// The server associates a new thread to it
			while (true)
			{ 
				if (nb_thread < nb_players){
					for (int i=0; i<nb_players; i++){
						if(tm.isFree(i)){
							Socket client = listen.accept();
							tm.getConnexions()[i] = new Connexion (client, i, w, tm);
							tm.setFree(i, false);
							tm.getConnexions()[i].start();
							tm.plusNbThreads();
							break;
						}
					}
					
					

				}	
			}
		} 
		catch (IOException e) { 
			System.err.println(e.getMessage()); 
			System.exit(1);
		}
	}
	
	public static void main(String[] args) {
		System.out.println("server executed..."); 
		new Server();
	}

}
